package com.audiocn.dc;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.audiocn.Utils.Log;
import com.audiocn.Utils.Utils;
import com.audiocn.manager.BaseManager;
import com.audiocn.manager.PostersManager;
import com.audiocn.model.PostersModel;
import com.audiocn.poster.Application;
import com.audiocn.poster.Configs;
import com.audiocn.poster.R;
import com.audiocn.widget.PostersGallery;
import com.audiocn.widget.PostersGallery.OnPostersGalleryLitener;

/**
 * 逛逛画报列表DC
 */
public class PostersDC extends BaseDC implements OnPostersGalleryLitener, OnItemSelectedListener {

	public static boolean isNotify = true;
	public static boolean isFirst = false;
	Button chanel;
	public  TextView title;
	public PostersGallery pGallery;
	ProgressDialog progress;
	ProgressBar pb;
	MyAdapter adapter;
	List<List<PostersModel>> posters = null;
	float start = 0;
	float end = 0;
	
	int firCom = -1;
	
	boolean isDiss = false;
	
	public int sign = -1;
	List<Thread> threads;
	
	float downX = -1;
	float downY = -1;
	
	float gWidth = 0;
	float gHight = 0;
	
	public Bitmap bmp;
	
//	float motions;
	int i = 0;
	
	View getImageLayout = null;
	
	public PostersDC(Context context, int layoutId, final BaseManager manager) {
		super(context, layoutId, manager);
		posters = new ArrayList<List<PostersModel>>();
		
		getImageLayout = this.findViewById(R.id.getImageLayout);
		pb = (ProgressBar) this.findViewById(R.id.pl_progress);
		pb.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Log.e("pb.setOnTouchListener", "pb.setOnTouchListener");
				isDiss = true;
				dismissGettingImage();
				return true;
			}
		});
		chanel = (Button) findViewById(R.id.pChanel);
		title = (TextView) findViewById(R.id.pl_title);
		title.setText(context.getSharedPreferences(PostersManager.USER_POSTERS_CHANEL, Context.MODE_APPEND).getString("chanel_name", "女人"));
		chanel.setOnClickListener(this);
		pGallery = (PostersGallery) findViewById(R.id.p_gallery);
		adapter = new MyAdapter(context);
		pGallery.setAdapter(adapter);
		pGallery.setClickable(false);
		pGallery.setOnItemSelectedListener(this);
		pGallery.setPosterListener(this);
		threads = new ArrayList<Thread>();
		progress = new ProgressDialog(context);
		
		bmp = BitmapFactory.decodeResource(context.getResources(), Application.getLayoutId(R.drawable.default_img));
		
		progress.setOnKeyListener(new DialogInterface.OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					manager.sendEmptyMessage(Configs.STOP_ALL);
				}
				return false;
			}
		});
	}

	@Override
	public void onClicked(View v) {
		if(Application.dcEngine.notAnimition()) {
			if (v.getTag() != null && (v.getTag() instanceof PostersModel)) {
				manager.sendMessage(manager.obtainMessage(5, ((PostersModel)v.getTag()).getId(), 0));
				return;
			}
			switch (v.getId()) {
			case R.id.pChanel:
				manager.sendEmptyMessage(9);
				break;
			default:
				manager.sendEmptyMessage(v.getId());
				break;
			}
		}
	}

	public List<List<PostersModel>> getPosters() {
		return posters;
	}

	public void setPosters(List<List<PostersModel>> posters) {
		this.posters = posters;
	}
	
	public class MyAdapter extends BaseAdapter {
		private LayoutInflater layoutInflater = null;
		public MyAdapter(Context context) {
			layoutInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return posters.size();
		}

		@Override
		public Object getItem(int position) {
			return posters.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position != sign) {
				Log.e("getView", "position:" + position + " sign:" + sign);
				isDiss = false;
			}
			View v = null;
			ViewHolder viewHolder;
			Gallery.LayoutParams param = new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			if (convertView == null) {
				viewHolder = new ViewHolder();
				v = layoutInflater.inflate(R.layout.posters_item, null);
				viewHolder.image1 = (ImageView) v.findViewById(R.id.p_img01);
				viewHolder.image2 = (ImageView) v.findViewById(R.id.p_img02);
				viewHolder.image3 = (ImageView) v.findViewById(R.id.p_img03);
				viewHolder.image4 = (ImageView) v.findViewById(R.id.p_img04);
				v.setTag(viewHolder);

			} else {
				v = convertView;
				viewHolder = (ViewHolder) v.getTag();
			}
			try{
				if (position < posters.size()) {
					sign = position;
					if (position == (posters.size() - 1)) {
						manager.sendEmptyMessage(14);
					}
					
					List<PostersModel> p = posters.get(position);
					for(int j=0; j<4; j++) {
						if (position < posters.size() && position >= 0) {
							if (posters.get(position).get(j) != null) {
 								posters.get(position).get(j).setItemImage(fitSizePic(position, j));
							}
						}
					}
					int i = 0;
					dismissProgress();
					while (i < p.size()) {
						if (i == 0) {
							if (posters.get(position).get(i).getItemImage() == null) {
								showGetingImage();
								viewHolder.image1.setImageBitmap(bmp);
							} else {
								viewHolder.image1.setImageBitmap(p.get(i).getItemImage());
							}
						} else if (i == 1) {
							if (posters.get(position).get(i).getItemImage() == null) {
								showGetingImage();
								viewHolder.image2.setImageBitmap(bmp);
							} else {
								viewHolder.image2.setImageBitmap(p.get(i).getItemImage());
							}
						} else if (i == 2) {
							if (posters.get(position).get(i).getItemImage() == null) {
								showGetingImage();
								viewHolder.image3.setImageBitmap(bmp);
							} else {
								viewHolder.image3.setImageBitmap(p.get(i).getItemImage());
							}
						} else if (i == 3) {
							if (posters.get(position).get(i).getItemImage() == null) {
								showGetingImage();
								viewHolder.image4.setImageBitmap(bmp);
							} else {
								viewHolder.image4.setImageBitmap(p.get(i).getItemImage());
							}
						}
						i ++;
					}
					for(int j=0; j<4; j++) {
						if ((position - 2) >= 0) {
							if (posters.get(position - 2).get(j) != null && posters.get(position - 2).get(j).getItemImage() != null) {
								posters.get(position - 2).get(j).getItemImage().recycle();
								posters.get(position - 2).get(j).setItemImage(null);
							}
						}
						if ((position + 2) < posters.size()) {
							if (posters.get(position + 2).get(j) != null && posters.get(position + 2).get(j).getItemImage() != null) {
								posters.get(position + 2).get(j).getItemImage().recycle();
								posters.get(position + 2).get(j).setItemImage(null);
							}
						}
					}
					for(int j=0; j<4; j++) {
						if ((position + 1) < posters.size()) {
							if (posters.get(position + 1).get(j) != null && posters.get(position + 1).get(j).getItemImage() == null) {
								posters.get(position + 1).get(j).setItemImage(fitSizePic(position + 1, j));
							}
						}
						if ((position - 1) >= 0) {
							if (posters.get(position - 1).get(j) != null && posters.get(position - 1).get(j).getItemImage() == null) {
								posters.get(position - 1).get(j).setItemImage(fitSizePic(position - 1, j));
							}
						}
					}
				}
				if (!isNotify && isFirst && ((position == (posters.size() - 1)))) {
					Toast.makeText(context, "最后了..", 1).show();
				}
				v.setLayoutParams(param);
				System.gc();
				System.gc();
			} catch(OutOfMemoryError e) {
				e.printStackTrace();
				System.gc();
			}
			return v;
		}

	}
	
	public static final class ViewHolder {
		public ImageView image1;
		public ImageView image2;
		public ImageView image3;
		public ImageView image4;
	}
	
	public MyAdapter getAdapter() {
		return adapter;
	}

	public void dismissProgress() {
		Log.e("dismissProgress", "dismissProgress");
		getImageLayout.setVisibility(View.GONE);		
	}

	public void setAdapter(MyAdapter adapter) {
		this.adapter = adapter;
	}

	public Gallery getListView() {
		return pGallery;
	}

	public void setListView(PostersGallery pGallery) {
		this.pGallery = pGallery;
	}
	
	public  List<List<PostersModel>> getData() {
		return this.posters;
	}
	public void showTipDialog(String msg) {
		Toast.makeText(context, msg, 0).show();
	}
	public void showDialog() {
		progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progress.setIndeterminate(false);
		progress.setMessage("正在请求数据....");
		progress.setMax(1000);
		progress.setProgress(1);
		progress.show();
	}
	
	public void dismissDialog() {
		if (progress != null && progress.isShowing()) {
			progress.dismiss();
		}
	}
	
	public static Bitmap fitSizePic(byte[] f) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		Bitmap resizeBmp = null;
		if (f.length < 20480) { // 0-20k
		 opts.inSampleSize = 2;
		} else if (f.length < 51200) { // 20-50k
		 opts.inSampleSize = 2;
		}else if (f.length < 307200) { // 50-300k
		 opts.inSampleSize = 4;
		} else if (f.length < 819200) { // 300-800k
		 opts.inSampleSize = 6;
		} else if (f.length < 1048576) { // 800-1024k
		 opts.inSampleSize = 8;
		} else {
		 opts.inSampleSize = 10;
		}
		try{
			resizeBmp = BitmapFactory.decodeByteArray(f, 0, f.length);
		} catch(OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
			return null;
		}
		return resizeBmp;
	}
	
	public Bitmap fitSizePic(int position, int i) {
		if (position >= posters.size()) {
			return null;
		}
		Bitmap resizeBmp = null;
		try{
			if (PostersManager.imgs_posters.get(posters.get(position).get(i).getBigImage()) == null) {
				return null;
			} else {
				resizeBmp = BitmapFactory.decodeFile(PostersManager.imgs_posters.get(posters.get(position).get(i).getBigImage()));
			}
			
		} catch(OutOfMemoryError e) {
			e.printStackTrace();
			System.gc();
			return null;
		}
		return resizeBmp;
	}
	
	public byte[] getData(InputStream in){
		if (in == null) {
			return null;
		}
		ByteArrayOutputStream bs = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		try {
			while((len = in.read(b, 0, b.length)) != -1) {
				bs.write(b, 0, len);
			}
			return bs.toByteArray();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
    /**
     * 获取图片时显示闪烁动画
     */
    public void showGetingImage() {
    	if (!isDiss) {
    		pb.requestFocus();
    		getImageLayout.setVisibility(View.VISIBLE);
		}
    }
    
    /**
     * 图片获取完后动画消失
     */
    private void dismissGettingImage() {
    	Log.e("dismissGettingImage", "dismissGettingImage");
    	AlphaAnimation aa = new AlphaAnimation(1, 0);
    	aa.setDuration(800);
    	aa.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
				
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				
				getImageLayout.setVisibility(View.GONE);
			}
		});
    	getImageLayout.startAnimation(aa);
    }

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		if (Utils.isNetworkValidate()) {
			manager.removeMessages(12);
			manager.sendMessageDelayed(manager.obtainMessage(12, position, 0), 200);
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
	}

	@Override
	public void OnClickPlace(int place) {
		if (posters == null || posters.size() <= sign || sign < 0) {
			return;
		}
		switch (place) {
		case PostersGallery.PLACE_LEFT_TOP:
			break;
		case PostersGallery.PLACE_RIGHT_TOP:
			if (posters.get(sign) == null || posters.get(sign).size() <= 1) {
				return;
			}
			break;
		case PostersGallery.PLACE_LEFT_BOTTOM:
			if (posters.get(sign) == null || posters.get(sign).size() <= 2) {
				return;
			}
			break;
		case PostersGallery.PLACE_RIGHT_BOTTOM:
			if (posters.get(sign) == null || posters.get(sign).size() <= 3) {
				return;
			}
			break;
		default:
			break;
		}
		manager.sendMessage(manager.obtainMessage(5, posters.get(sign).get(place).getId(), 0));
	}
	
}
